<slot/>

Posted on 2023-04-20 by

henrikvilhelmberglund

Slots are a way to compose components .

Compose components?

In HTML you can have elements inside of elements, for example <div><span></span></div> . With slots we can do the same thing, we can put elements or other components inside of our components.

Here is a simple example. We can put the slot anywhere, before or after the text. Here it is inside an if block that is controlled by the checkbox.
Hello world
<script>
	import Component from "./Component.svelte";
</script>

<div>
	Hello
	<span>world</span>
</div>

<Component>
	Hello
	<span>world</span>
</Component>

<style>
</style>

What if nothing was passed into a slot? We can have a fallback :

We can have a fallback by adding content inside of the slot tag.
0
<script>
	import Component2 from "./Component2.svelte";

  let count = 0;
</script>

<div>
	{count}
	<button on:click={() => count++}>+</button>
</div>

<Component2>
	{count}
	<button on:click={() => count--}>-</button>
</Component2>

<Component2></Component2>

<style>
</style>

Finally we can have named slots . Note that a slot without a name is named default so you can't use that.

If we want a named slot with a single element we can add it as a slot attribute, but if we want to group multiple elements we can have a slot template with a slot attribute which wraps all elements inside.
0
Element for footer
Footer slot with fallback
Header slot with fallback
<script>
	import Component3 from "./Component3.svelte";

	let count = 0;
</script>

<Component3>
	<slot:template slot="header">
		{count}
		<button on:click={() => count--}>-</button>
	</slot:template>
	<div slot="footer">Element for footer</div>
</Component3>

<Component3 />

<style>
	/* styles are still scoped so even if we're adding something to a slot the styles come from this component! */
	button {
		font-size: 48px;
	}
</style>